package com.csw.android.androidtest.module.thread;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.csw.android.androidtest.R;
import com.csw.android.dev_utils.ui.BaseFragment;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * 多线程测试，android提供了一个主线程，并且开启了loop循环执行任务，耗时的任务可以异步执行，但更新界面必须在主线程
 * 多线程执行时间并不一致，并不是说先start的线程就一定先执行完。
 */
public class ThreadTest extends BaseFragment {
    protected StringBuffer logs = new StringBuffer();
    protected View run;
    protected TextView log;

    @Override
    public int getContentViewID() {
        return R.layout.fragment_thread_test;
    }

    @Override
    public void initView(@NotNull View rootView, @Nullable Bundle savedInstanceState) {
        super.initView(rootView, savedInstanceState);
        run = rootView.findViewById(R.id.run);
        log = rootView.findViewById(R.id.log);
    }

    @Override
    public void initListener() {
        super.initListener();
        run.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logs = new StringBuffer();
                appendLog();
                for (int i = 1; i <= 10; i++) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            appendLog();
                        }
                    }, "thread " + i).start();
                }
            }
        });
    }

    private void appendLog() {
        synchronized (this) {
            logs.append("runOn___>");
            logs.append(Thread.currentThread().getName());
            logs.append("\n");
            updateLog();
        }
    }

    protected void updateLog() {
        final TextView l = log;
        if (l != null) {
            l.post(new Runnable() {
                @Override
                public void run() {
                    l.setText(logs.toString());
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        run = null;
        log = null;
        super.onDestroyView();
    }
}
